import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '@/store'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 0, // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    // console.log(config)
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = token // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    Message({
      message: '网络出错了,请稍后再试试',
      type: 'error',
      duration: 3 * 1000,
    })
    console.log(error) // for debug
    return Promise.reject(error)
  },
)

// respone拦截器
service.interceptors.response.use(
  response => {
    // 200 返回
    if (process.env.BASE_API === '/memberapi') {
      return response.data.data
    } else {
      if (response.data.data) {
        if (response.data.message) {
          response.data.data['message'] = response.data.message
        }
        return response.data.data
      } else {
        return response.data
      }
    }
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break

        case 401:
          error.message = '身份验证已过期,请重新登录'
          break

        case 403:
          error.message = '拒绝访问'
          break

        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break

        case 408:
          error.message = '请求超时'
          break

        case 500:
          error.message = '服务器内部错误'
          break

        case 501:
          error.message = '服务未实现'
          break

        case 502:
          error.message = '网关错误'
          break

        case 503:
          error.message = '服务不可用'
          break

        case 504:
          error.message = '网关超时'
          break

        case 505:
          error.message = 'HTTP版本不受支持'
          break

        default:
      }

      Message({ message: error.message, type: 'error', duration: 5 * 1000 })
      if (error.response.status === 401) {
        setTimeout(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }, 2000)
      }
    }

    return Promise.reject(error)
  },
)

export default service
